package com.itheima.security;

import com.itheima.pojo.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
public class SpringSecurityService implements UserDetailsService {
    //模拟数据库中的用户数据
    public  static Map<String, SysUser> map = new HashMap<>();
    public static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    static {
        SysUser user1 = new SysUser();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));


        SysUser user2 = new SysUser();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    /*
        根据用户加载用户对象
            1. 根据用户名从数据库查询用户对象
            2. 把数据库查询的对象进行封装返回给安全框架

     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1. 模拟从数据库中查询用户对象
        SysUser sysUser = map.get(username);

        //2. 把数据库查询的对象进行封装返回给安全框架
        //创建一个权限集合对象
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //创建权限对象
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
        SimpleGrantedAuthority authority1 = new SimpleGrantedAuthority("add");
        authorities.add(authority);
        authorities.add(authority1);
        User user = new User(sysUser.getUsername(),sysUser.getPassword(), authorities);
        return user;
    }
}
